const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
export default class Promise{
    // 声明私有的状态
    #state = PENDING;
    // 声明私有状态值
    #result = undefined;
    // 定义更改状态为成功的方法
    static #resolve = function(value){
        // 如果状态已经修改过，不允许再次修改
        if(this.#state !== PENDING) return;
        // 将状态更改为成功
        this.#state = FULFILLED;
        this.#result = value;
    }
    // 定义更改状态为失败的方法
    static #reject = function(value){
        // 如果状态已经修改过，不允许再次修改
        if(this.#state !== PENDING) return;
        // 将状态更改为失败
        this.#state = REJECTED;
        this.#result = value;
    }
    constructor(executor) {
        try{
            executor(Promise.#resolve.bind(this),Promise.#reject.bind(this));
        }catch (err){
            Promise.#reject.call(this,err);
        }
    }
    // 接收两个函数（成功回调，失败回调）
    then(onResolved,onRejected){
        return new Promise((resolve,reject)=>{
            const common = (callback)=>{
                setTimeout(()=>{
                    try{
                        const value = callback(this.#result);
                        if(value instanceof Promise) value.then(resolve,reject);
                        else resolve(value);
                    }catch (err){
                        reject(err);
                    }
                });
            }
            // 判断当前实例的状态是否为成功，如果为成功调用成功回调
            if(this.#state === FULFILLED) common(onResolved);
            else if(this.#state === REJECTED) common(onRejected);
        })
    }
}